package com.example.demo.controller;

import com.example.demo.entity.AjaxResult;
import com.example.demo.service.FirmwareUpgradeService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 文件管理控制类
 */
@Controller //加入到IOC容器中
public class FileController { //关于File的controller类

    @Autowired
    FirmwareUpgradeService firmwareUpgradeService;

    @Value("${demo.dirPath}")
    private String dirPath;

    @GetMapping("/toUpload")
    public String toUpload(){
        return "/page/upload";
    }

    @PostMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile[] fileUpload, Model model) {
        //默认文件上传成功,并返回状态信息
        model.addAttribute("uploadStatus", "上传成功！");
        if(fileUpload.length == 1){
            MultipartFile file = fileUpload[0];
            //获取文件名以及后缀名 (获取原始文件名)
            String fileName = file.getOriginalFilename();
            //使用UUID + 原始文件名 来生成一个新的文件名
            fileName = UUID.randomUUID()+"_"+fileName;
            //指定文件上传的本地存储目录，不存在则提前创建
            File filePath = new File(dirPath);
            if(!filePath.exists()){filePath.mkdirs();}//创建该目录
            try {
                //执行“文件上传”的方法
                file.transferTo(new File(dirPath+fileName));
                AjaxResult ajax = AjaxResult.success();
                ajax.put("filename", fileName);
                ajax.put("filepath", "/download?filename="+fileName);
                return ajax;
            }
            catch (Exception e) {
                e.printStackTrace();
                //上传失败，返回失败信息
                model.addAttribute("uploadStatus","上传失败： "+e.getMessage());
                AjaxResult ajax = AjaxResult.error("上传失败： "+e.getMessage());
                return ajax;
            }
        }else{
            return AjaxResult.error("上传失败： 上传的文件不能大于1个");
        }
    }

    @GetMapping("/toDownload")
    public String toDownload(){
        return "page/download";
    }

    /**
     *  英文名称文件下载
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename){
        //指定要下载的文件根路径
        //创建该文件对象
        File file = new File(dirPath + File.separator + filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);
        }
        catch (Exception e) {e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
                    HttpStatus.EXPECTATION_FAILED);
        }
    }
}
